<?php

require_once 'version_fixes.php';

error_reporting(E_ALL);

function report_error($error_message, $stacktrace) {
	$now = date("Y-m-d H:i:s");
	$installation = current_root_url(); 
	$requested_page = current_request_url();
	$stacktrace = json_encode($stacktrace, JSON_PRETTY_PRINT);
	
	$context = json_encode(array(
		'$_SERVER'  => $_SERVER, 
		'$_SESSION' => isset($_SESSION) ? $_SESSION : array(), 
		'$_COOKIE'  => $_COOKIE, 
		'$_GET'     => $_GET, 
		'$_POST'    => $_POST, 
		'$_FILES'   => $_FILES
	), JSON_PRETTY_PRINT);
	
	$report = "
	
[$installation] $error_message
Time: $now
Url:  $requested_page
Stacktrace:
$stacktrace
	
Context:
$context
	";
	// Try to email error, if in production
	// TODO: what if mailing fails? Does execution stop?
	if (!(defined('DEBUG') and DEBUG) && ADMIN_EMAIL !== '') {
		LT_mail(ADMIN_EMAIL, "[Debug report] [$installation] " . $error_message, $report);
	}
	// TODO: Try to write error to database
	
	// Try to write error to file
	log_message('errors.log', $report);
	
	return $report;
}

function handleShutdown() {
	$error = error_get_last();
	if($error !== NULL){
		$info = "[SHUTDOWN] file:".$error['file']." | ln:".$error['line']." | msg:".$error['message'] .PHP_EOL;
		report_error("Discovered error at shutdown", $error['message']);
	}
}
register_shutdown_function('handleShutdown');

class ErrorOrWarningException extends Exception {
    
	protected $_context = null;
    
    public function getcontext() {
        return $this->_context;
    }
    
    public function set_context($value) {
        $this->_context = $value;
    }

    public function __construct( $code, $message, $file, $line, $context) {
        parent::__construct( $message, $code );

        $this->file = $file;
        $this->line = $line;
        $this->set_context($context);
    }
}

/**
 * Inspire to write perfect code. everything is an exception, even minor warnings.
 **/
function error_to_exception( $code, $message, $file, $line, $context) {
    throw new ErrorOrWarningException( $code, $message, $file, $line, $context);
}
set_error_handler('error_to_exception');